package com.toune.gdlocation.location

import android.Manifest
import android.app.Activity
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ListView
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.location.AMapLocation
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.services.core.PoiItem
import com.amap.api.services.help.Inputtips
import com.amap.api.services.help.InputtipsQuery
import com.amap.api.services.help.Tip
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.hjq.permissions.OnPermission
import com.hjq.permissions.XXPermissions
import com.qmuiteam.qmui.layout.QMUIButton
import com.qmuiteam.qmui.layout.QMUILinearLayout
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.toune.gdlocation.R


class GDLocationDialogFragment : BaseDialogFragment(), PoiSearch.OnPoiSearchListener,
    Inputtips.InputtipsListener {
    private var poiSearch: PoiSearch? = null
    private var activity: Activity? = null

    override fun onAttach(context: Context) {
        super.onAttach(requireContext())
        activity = context as AppCompatActivity
    }

    companion object {
        fun show(manager: FragmentManager, onSelectPoiItemListener: OnSelectPoiItemListener) {
            val args = Bundle()
            val fragment = GDLocationDialogFragment()
            fragment.onSelectPoiItemListener = onSelectPoiItemListener
            fragment.arguments = args
            fragment.show(manager, "GD")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(
            DialogFragment.STYLE_NORMAL,
            android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen
        )
    }

    internal var windowWidth = 360
    var mRootView: View? = null

    //初始化地图控制器对象
    var aMap: AMap? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        //先判断有没有权限
        if (!XXPermissions.hasPermission(
                context,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
            )
        ) {
            //没有权限
            XXPermissions.with(context)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION)
                .permission(Manifest.permission.ACCESS_FINE_LOCATION)
                .request(object : OnPermission {
                    override fun hasPermission(granted: List<String>, all: Boolean) {
                        if (all) {
                            //同意了位置权限
                            GDLocationUtil(
                                requireContext(),
                                object : GDLocationUtil.OnLocChangeListener {
                                    override fun onChange(loc: AMapLocation) {
                                        if (location == null) {
                                            location = loc
                                            var latLng = LatLng(loc.latitude, loc.longitude)
                                            val cameraUpdate = CameraUpdateFactory.newLatLng(latLng)
                                            val marker: Marker = aMap!!.addMarker(
                                                MarkerOptions().position(latLng).title(loc.poiName)
                                                    .snippet(loc.city)
                                            )
                                            aMap!!.moveCamera(cameraUpdate)
                                            queryStr = loc.poiName
                                            queryAdd()
                                        }
                                        location = loc
                                    }
                                })
                        }
                    }

                    override fun noPermission(denied: List<String>, never: Boolean) {
                        if (!never) {
                        }
                    }
                })
        } else {
            GDLocationUtil(requireContext(), object : GDLocationUtil.OnLocChangeListener {
                override fun onChange(loc: AMapLocation) {
                    if (location == null) {
                        location = loc
                        var latLng = LatLng(loc.latitude, loc.longitude)
                        val cameraUpdate = CameraUpdateFactory.newLatLng(latLng)
                        val marker: Marker = aMap!!.addMarker(
                            MarkerOptions().position(latLng).title(loc.poiName).snippet(loc.city)
                        )
                        aMap!!.moveCamera(cameraUpdate)
                        queryStr = loc.poiName
                        queryAdd()
                    }
                    location = loc
                }
            })
        }
        mRootView = inflater.inflate(R.layout.dialog_fragment_gd_location, container)
        dialog!!.setCanceledOnTouchOutside(false)
        val window = dialog!!.window
        window!!.setBackgroundDrawable(ColorDrawable(-0x80000000))
        val params = window.attributes
        params.gravity = Gravity.CENTER
        params.width = WindowManager.LayoutParams.MATCH_PARENT
        params.height = WindowManager.LayoutParams.MATCH_PARENT
        window.attributes = params
        initView(mRootView, savedInstanceState)
        return mRootView
    }

    var currentPage = 1
    var queryStr = ""
    var location: AMapLocation? = null
    lateinit var mapRelativeLayout: MapRelativeLayout
    lateinit var zzRv: RelativeLayout
    lateinit var locationRclView: RecyclerView
    lateinit var mapView: MapView
    lateinit var tipListView: ListView
    lateinit var refreshLayout: SmartRefreshLayout
    lateinit var addressEt: EditText
    lateinit var addressLv: QMUILinearLayout
    lateinit var cancelBtn: QMUIButton
    lateinit var sureBtn: QMUIButton
    private fun initView(view: View?, savedInstanceState: Bundle?) {
        mapRelativeLayout = mRootView!!.findViewById(R.id.mapRelativeLayout)
        zzRv = mRootView!!.findViewById(R.id.zzRv)
        locationRclView = mRootView!!.findViewById(R.id.locationRclView)
        mapView = mRootView!!.findViewById(R.id.mapView)
        tipListView = mRootView!!.findViewById(R.id.tipListView)
        refreshLayout = mRootView!!.findViewById(R.id.refreshLayout)
        addressEt = mRootView!!.findViewById(R.id.addressEt)
        addressLv = mRootView!!.findViewById(R.id.addressLv)
        cancelBtn = mRootView!!.findViewById(R.id.cancelBtn)
        sureBtn = mRootView!!.findViewById(R.id.sureBtn)

        mapRelativeLayout.setMapContainer(zzRv)
        mapRelativeLayout.setRecyclerView(locationRclView)
        mapView.onCreate(savedInstanceState)
        if (aMap == null) {
            aMap = mapView.map
            aMap!!.moveCamera(CameraUpdateFactory.zoomTo(15f))
//            var mUiSettings = aMap!!.uiSettings
//            mUiSettings.isZoomControlsEnabled = false
//            mUiSettings.isMyLocationButtonEnabled = true //显示默认的定位按钮
//            aMap!!.isMyLocationEnabled = true;// 可触发定位并显示当前位置
        }

        cancelBtn.setOnClickListener {
            dismissAllowingStateLoss()
        }

        sureBtn.setOnClickListener {
            if (onSelectPoiItemListener != null) {
                val myPoiItem = MyPoiItem()
                myPoiItem.poiItem = selectedPoiItem!!
                onSelectPoiItemListener!!.onSelected(myPoiItem)
            }
            dismissAllowingStateLoss()
        }

        addressEt.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                queryStr = addressEt.text.toString()
                tipListView.visibility = View.GONE
                queryAdd()
            }
            return@setOnEditorActionListener true
        }

        refreshLayout.setEnableRefresh(false)
        refreshLayout.setOnLoadMoreListener {
            currentPage++
            queryAdd()
        }
        addressEt.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val inputquery = InputtipsQuery(s.toString(), "")
                val inputTips = Inputtips(context, inputquery)
                inputTips.setInputtipsListener(this@GDLocationDialogFragment)
                inputTips.requestInputtipsAsyn()
            }
        })

    }

    private fun queryAdd() {
        var query = PoiSearch.Query(queryStr, "", "")
        query.pageSize = 20 // 设置每页最多返回多少条poiitem
        query.pageNum = currentPage //设置查询页码
        if (poiSearch == null) {
            poiSearch = PoiSearch(context, query)
        } else {
            poiSearch!!.query = query
        }
//        if (location != null) {
//            poiSearch!!.bound = PoiSearch.SearchBound(LatLonPoint(location!!.latitude,
//                    location!!.longitude), 10000000, true) //设置周边搜索的中心点以及半径
//        }
        poiSearch!!.setOnPoiSearchListener(this)
        poiSearch!!.searchPOIAsyn()
    }

    override fun onDestroy() {
        super.onDestroy()
        mapView.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapView.onPause()
    }

    override fun onPoiItemSearched(p0: PoiItem?, p1: Int) {

    }

    val poiSearchs = ArrayList<PoiItem>()
    override fun onPoiSearched(poiResult: PoiResult?, p1: Int) {
        if (poiResult == null) {
            return
        }
        if (poiResult.searchSuggestionCitys.size > 0 && poiResult.pois.size <= 0) {
            queryStr = poiResult.searchSuggestionCitys[0].cityName + queryStr
            queryAdd()
            return
        }
        if (currentPage == 1) {
            poiSearchs.clear()
        } else {
            refreshLayout!!.finishLoadMore()
        }
        poiSearchs.addAll(poiResult!!.pois)
        setPoiAdapter()
    }

    var poiAdapter: PoiAdapter? = null
    var selectedPoiItem: PoiItem? = null
    private fun setPoiAdapter() {
        if (poiAdapter == null) {
            poiAdapter = PoiAdapter(R.layout.item_poi, poiSearchs!!)
            locationRclView.layoutManager = LinearLayoutManager(context)
            locationRclView.adapter = poiAdapter
            poiAdapter!!.setOnItemClickListener { adapter, view, position ->
                setSelect(position)
            }
        } else {
            poiAdapter!!.notifyDataSetChanged()
        }
        if (poiSearchs.isNotEmpty()) {
            setSelect(0)
        }
    }

    fun setSelect(position: Int) {
        poiAdapter!!.setSelectPos(position)
        selectedPoiItem = poiSearchs[position]
        val latLonPoint = selectedPoiItem!!.latLonPoint
//                val aOptions = AMapOptions()
        var latLng = LatLng(latLonPoint.latitude, latLonPoint.longitude)
//                aOptions.camera(CameraPosition(latLng, 10f, 0f, 0f))
        val cameraUpdate = CameraUpdateFactory.newLatLng(latLng)
        val marker: Marker = aMap!!.addMarker(
            MarkerOptions().position(latLng).title(selectedPoiItem!!.title)
                .snippet(selectedPoiItem!!.snippet)
        )
        aMap!!.moveCamera(cameraUpdate)
    }

    var adapter: ArrayAdapter<MyTip>? = null
    var myTips = ArrayList<MyTip>()
    override fun onGetInputtips(p0: MutableList<Tip>?, p1: Int) {
        if (p0 == null) {
            return
        }
        if (tipListView.visibility == View.GONE) {
            tipListView.visibility = View.VISIBLE
        }
        myTips.clear()
        for (i in p0!!) {
            myTips.add(MyTip(i))
        }
        if (adapter != null) {
            adapter!!.notifyDataSetChanged()
        } else {
            adapter =
                ArrayAdapter<MyTip>(requireContext(), android.R.layout.simple_list_item_1, myTips)
            tipListView.adapter = adapter
            tipListView.setOnItemClickListener { parent, view, position, id ->
                tipListView.visibility = View.GONE
                currentPage = 1
                queryStr = myTips[position].tip.name
                queryAdd()
                myTips.clear()
                adapter!!.notifyDataSetChanged()
            }
        }
    }

    var onSelectPoiItemListener: OnSelectPoiItemListener? = null

    interface OnSelectPoiItemListener {
        fun onSelected(poiItem: MyPoiItem)
    }
}